package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Service service;
    private Map<String,HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }
    public RequestProcessor(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String url = request.getUrl();
            if("/favicon.ico".equals(url))return;
            String[] uriArr = url.split("/");
            String contextPath = "";
            String uri = "";
            if(uriArr.length > 2){
                contextPath = uriArr[1];
                uri = url.substring(contextPath.length()+1);
            }else{
                uri = url;
            }
            if(service.getHost().getContextMap().containsKey(contextPath)){
                // 动态资源servlet请求
                Context context = service.getHost().getContextMap().get(contextPath);
                HttpServlet httpServlet = context.getServletMap().get(uri);
                httpServlet.service(request,response);
            }else{
                // 静态资源处理
                response.outputHtml(request.getUrl());
            }

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
